<template>
  <div>
    <!-- 交付经理填写项目定级信息 -->
    <div class="desc-item">
      <div class="form-item">项目定级信息</div>
      <div class="table-title" > 售前ICT填报信息 </div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectGradingDetails.preProjectGradingInfoDesc"
        :readOnly="true"
        :column="2"
      />
      <div class="table-title" > 售中交付填报信息 </div>
      <DynamicDescription
        ref="dynamicDescription"
        :descriptions="projectGradingDetails.projectGradingInfoDesc"
        :descriptForm="projectGradingDetails.projectGradingInfoForm"
        :readOnly="!isShowApprovalOperation('first')"
        :column="2"
      />
      <div class="table-title" > 自主能力填报信息 </div>
      <AutonomousAbilitySelector
        :descriptions="projectGradingDetails.autonomousAbilityDesc"
        :readOnly="!isShowApprovalOperation('first')"
        ref="autonomousSelector"
       />
      <div v-if="projectFiles[processStageName].length > 0">
        <div class="table-title">上传附件</div>
        <FilesUpload
          ref="filesUploadRef"
          :fileTypes="projectFiles[processStageName]"
          :projectInfo="projectInfo"
          :readOnly="!isShowApprovalOperation('first')"
          @getProjectFilesInfo="$emit('getProjectFilesInfo')"
        />
      </div>
      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <div class="table-title" > 下一环节 - 建设单位部门经理审批 </div>
          <DynamicDescription
            :descriptions="projectGradingDetails.projectGradingSecondInfoDesc"
            :readOnly="true"
            :column="1"
          />
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'projectManager', projectInfo.construction_department_manager_id)"
          >同意</el-button>
        </div>
      </div>
      <!-- 三级经理审批 -->
      <div v-if="isShowApprovalOperation('second')">
        <div class="form-item" >审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData"
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="danger"
            size="default"
            @click="approvalProcess('refuse', 'constructionDepartmentManager')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'constructionDepartmentManager')"
          >同意</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesUpload from '@/views/project/projectDetails/components/FilesUpload.vue';
import { ref, toRefs } from 'vue'
import AutonomousAbilitySelector from '@/views/project/projectDetails/components/AutonomousAbilitySelector.vue';
import ApprovalOpinion from '@/views/project/components/ApprovalOpinion.vue'
// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo']);

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  projectGradingDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const { isShowApprovalOperation, projectInfo, projectGradingDetails, processStageName, taskName, role, processList } = toRefs(props);

// 动态详情组件ref对象
const dynamicDescription = ref()
const autonomousSelector = ref(null)
// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()
// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);

const approvalProcess = async (result, currentRole, nextRoleId) => {
  try {
    if (result === 'agree') {
      await Promise.all([
        dynamicDescription.value.validateForm(),
        // autonomousSelector.value.validateForm(),
        approvalOpinionRef.value.validateForm()
      ])
      if (filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
        return;
      }
    } else {
      approvalOpinionRef.value.validateForm()
    }

    // 表单验证通过，执行提交逻辑
    ElMessageBox.confirm(`是否${result === 'agree' ? '同意' : '驳回'}该流程单？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const approvalFormData = dynamicDescription.value.getFormData()
      const autonomousData = autonomousSelector.value?.getFormData()
      if (result === 'agree') {
        const agreeProcessData = {
          assignedUserIds: [nextRoleId],
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '同意',
          copyUserIds: [],
          variables: {}
        }
        
        if (currentRole === 'projectManager') {
          projectInfo.value = Object.assign(projectInfo.value, approvalFormData)
          projectInfo.value = Object.assign(projectInfo.value, autonomousData)
        }

        const agreeData = {
          update: true,
          project_index_do: projectInfo.value,
          task_approve_req_vo: agreeProcessData
        }

        if (currentRole === 'projectManager') {
          await IctApi.agreeProjectProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        } else {
          await IctApi.agreeProjectGradingDepartmentManagerProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        }

      } else if (result === 'refuse') {
        const refuseData = {
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '不同意'
        }
        await IctApi.refuseGradingProcess(refuseData).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }
  
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

</style>